
import api from '@/utils/api'
import { resetRouter } from '@/router'

const state = {
  roleLevel: '',
  token: '',
  userInfo: '',
  permissionRoutes: '',
  msgNum: '',
  orgId: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROUTER: (state, router) => {
    state.permissionRoutes = router
  },
  SET_MSGNUM: (state, num) => {
    state.msgNum = num
  },
  SET_ORGID: (state, id) => {
    state.orgId = id
  }
}

const actions = {
  // user login
  login({ dispatch, commit }, userInfo) {
    return new Promise((resolve, reject) => {
      if(userInfo.account==='admin'&&userInfo.password==='admin'){
        commit('SET_TOKEN', true)
        commit('SET_INFO', {userName:userInfo.account,nickName:userInfo.account,type:userInfo.type})
        resolve(true)
      }else{
        reject()
      }
      // api.post(`/login`, userInfo).then(response => {
      //   commit('SET_TOKEN', response)
      //   commit('SET_INFO', {userName:userInfo.account,nickName:userInfo.account})
      //   resolve(response)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  // user logout
  logout({ commit, rootState }) {
    return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        commit('SET_ROUTER', '')
        rootState.tabs.taskTabs = []
        rootState.tabs.workTabs = []
        rootState.tabs.dataTabs = []
        rootState.tabs.tableTabs = []
        rootState.tabs.computedTabs = []
        window.addRouteFlag = false
        sessionStorage.removeItem('vuex')
        resetRouter()
        resolve()
        return
      api.post(`/users/logout`, {}).then(response => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        commit('SET_ROUTER', '')
        rootState.tabs.taskTabs = []
        rootState.tabs.workTabs = []
        rootState.tabs.dataTabs = []
        rootState.tabs.tableTabs = []
        rootState.tabs.computedTabs = []
        window.addRouteFlag = false
        sessionStorage.removeItem('vuex')
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getRouter({ commit }, userId) {
    return new Promise(resolve => {
      resolve(state.permissionRoutes)
      api.get(`/menu/user/${userId}`).then(res => {
        commit('SET_ROUTER', res)
        resolve()
      })
    })
  },
  getMsgNum({ commit }) {
    api('/resources/resMessage/findMsgCount', {}).then(res => {
      commit('SET_MSGNUM', res)
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
